<template>
  <div class="dify-workflow-chat">
    <div class="chat-header">
      <h2>🤖 Dify 工作流聊天</h2>
      <div class="header-controls">
        <div class="api-status">
          <button @click="difyStore.checkApiHealth()" :disabled="difyStore.isConnecting" class="status-btn">
            <span :class="['status-dot', getStatusClass()]"></span>
            {{ getStatusText() }}
          </button>
        </div>
        <div class="user-info">
          <span class="user-id">用户: {{ difyStore.currentUserId }}</span>
          <button @click="difyStore.regenerateUserId()" class="regenerate-btn" title="重新生成用户ID">
            🔄
          </button>
        </div>
        <button @click="difyStore.clearMessages()" class="clear-btn">
          清空聊天
        </button>
      </div>
    </div>

    <div class="chat-container">
      <div class="messages-area" ref="messagesArea">
        <div v-if="difyStore.messages.length === 0" class="welcome-message">
          <div class="welcome-content">
            <h3>👋 欢迎使用 Dify 工作流</h3>
            <p>您可以输入任何问题或指令，AI将通过工作流为您处理。</p>
            <div class="example-inputs">
              <h4>示例输入：</h4>
              <div class="example-item" @click="setExampleInput('普钢综合,2025.1.2-2.2的数据，并画出其相关的趋势图表。')">
                普钢综合,2025.1.2-2.2的数据，并画出其相关的趋势图表。
              </div>
              <div class="example-item" @click="setExampleInput('分析最近一个月的销售数据趋势')">
                分析最近一个月的销售数据趋势
              </div>
              <div class="example-item" @click="setExampleInput('生成本月度工作报告摘要')">
                生成本月度工作报告摘要
              </div>
            </div>
          </div>
        </div>

        <div 
          v-for="message in difyStore.messages" 
          :key="message.id"
          :class="['message', message.type]"
        >
          <div class="message-avatar">
            <span v-if="message.type === 'user'">👤</span>
            <span v-else-if="message.type === 'assistant'">🤖</span>
            <span v-else>ℹ️</span>
          </div>
          <div class="message-content">
            <div class="message-header">
              <span class="message-type">{{ getMessageTypeLabel(message.type) }}</span>
              <span class="message-time">{{ formatTime(message.timestamp) }}</span>
              <span v-if="message.status" :class="['message-status', message.status]">
                {{ getStatusLabel(message.status) }}
              </span>
            </div>
            <div class="message-text">
              <div 
                v-if="message.type === 'assistant'" 
                class="assistant-content markdown-content"
                v-html="renderMarkdown(message.content)"
              ></div>
              <div v-else>{{ message.content }}</div>
            </div>
          </div>
        </div>
      </div>

      <div class="input-area">
        <div v-if="difyStore.error" class="error-message">
          <span>❌ {{ difyStore.error }}</span>
          <button @click="difyStore.error = null" class="close-error">×</button>
        </div>
        
        <div class="input-container">
          <textarea
            v-model="inputText"
            @keydown.enter.prevent="handleEnterKey"
            :disabled="difyStore.isStreaming"
            placeholder="输入您的问题或指令..."
            class="message-input"
            rows="3"
            ref="inputRef"
          ></textarea>
          <button 
            @click="sendMessage"
            :disabled="!inputText.trim() || difyStore.isStreaming"
            class="send-btn"
          >
            {{ difyStore.isStreaming ? '发送中...' : '发送' }}
          </button>
        </div>
        
        <div class="input-tips">
          <span>按 Shift+Enter 换行，Enter 发送</span>
          <span>当前状态: {{ difyStore.isStreaming ? '正在处理...' : '就绪' }}</span>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, nextTick, onMounted, computed } from 'vue'
import { useDifyWorkflowStore } from '@/stores/difyWorkflow'
import { marked } from 'marked'

const difyStore = useDifyWorkflowStore()
const inputText = ref('')
const messagesArea = ref<HTMLElement>()
const inputRef = ref<HTMLTextAreaElement>()

function getStatusClass() {
  if (difyStore.isConnecting) return 'connecting'
  if (difyStore.apiHealth === true) return 'connected'
  if (difyStore.apiHealth === false) return 'disconnected'
  return 'unknown'
}

function getStatusText() {
  if (difyStore.isConnecting) return '检查中...'
  if (difyStore.apiHealth === true) return 'API 已连接'
  if (difyStore.apiHealth === false) return 'API 未连接'
  return '检查连接'
}

function getMessageTypeLabel(type: string) {
  const labels = {
    user: '用户',
    assistant: '助手',
    system: '系统'
  }
  return labels[type as keyof typeof labels] || type
}

function getStatusLabel(status: string) {
  const labels = {
    sending: '发送中',
    success: '成功',
    error: '失败'
  }
  return labels[status as keyof typeof labels] || status
}

function formatTime(date: Date) {
  return date.toLocaleTimeString('zh-CN', {
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  })
}

function setExampleInput(text: string) {
  inputText.value = "{}"
  inputRef.value?.focus()
}

// 渲染 Markdown 内容
function renderMarkdown(content: string): string {
  if (!content) return ''
  
  // 配置 marked 选项
  marked.setOptions({
    gfm: true, // 支持 GitHub Flavored Markdown
    breaks: true, // 支持换行
    sanitize: false // 允许 HTML
  })
  
  return marked(content) as string
}

async function sendMessage() {
  if (!inputText.value.trim() || difyStore.isStreaming) return

  const message = inputText.value.trim()
  inputText.value = ''

  try {
    await difyStore.sendMessage(message)
    await scrollToBottom()
  } catch (error) {
    console.error('发送消息失败:', error)
  }
}

function handleEnterKey(event: KeyboardEvent) {
  if (event.shiftKey) {
    // Shift+Enter 换行，不做处理
    return
  } else {
    // Enter 发送消息
    event.preventDefault()
    sendMessage()
  }
}

async function scrollToBottom() {
  await nextTick()
  if (messagesArea.value) {
    messagesArea.value.scrollTop = messagesArea.value.scrollHeight
  }
}

onMounted(() => {
  difyStore.checkApiHealth()
})
</script>

<style scoped>
.dify-workflow-chat {
  max-width: 1200px;
  margin: 0 auto;
  height: calc(100vh - 40px);
  display: flex;
  flex-direction: column;
  background-color: #f8f9fa;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
}

.chat-header {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  padding: 16px 24px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 16px;
}

.chat-header h2 {
  margin: 0;
  font-size: 20px;
  font-weight: 600;
}

.header-controls {
  display: flex;
  align-items: center;
  gap: 16px;
  flex-wrap: wrap;
}

.status-btn {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 6px 12px;
  background: rgba(255, 255, 255, 0.2);
  border: 1px solid rgba(255, 255, 255, 0.3);
  border-radius: 6px;
  color: white;
  cursor: pointer;
  font-size: 12px;
  transition: background-color 0.2s;
}

.status-btn:hover {
  background: rgba(255, 255, 255, 0.3);
}

.status-dot {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  display: inline-block;
}

.status-dot.connected {
  background-color: #4ade80;
}

.status-dot.disconnected {
  background-color: #f87171;
}

.status-dot.connecting {
  background-color: #fbbf24;
  animation: pulse 1.5s infinite;
}

.status-dot.unknown {
  background-color: #9ca3af;
}

@keyframes pulse {
  0%, 100% { opacity: 1; }
  50% { opacity: 0.5; }
}

.user-info {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 12px;
}

.user-id {
  opacity: 0.9;
}

.regenerate-btn {
  background: none;
  border: none;
  color: white;
  cursor: pointer;
  padding: 4px;
  border-radius: 4px;
  transition: background-color 0.2s;
}

.regenerate-btn:hover {
  background: rgba(255, 255, 255, 0.2);
}

.clear-btn {
  padding: 6px 12px;
  background: rgba(255, 255, 255, 0.2);
  border: 1px solid rgba(255, 255, 255, 0.3);
  border-radius: 6px;
  color: white;
  cursor: pointer;
  font-size: 12px;
  transition: background-color 0.2s;
}

.clear-btn:hover {
  background: rgba(255, 255, 255, 0.3);
}

.chat-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  min-height: 0;
}

.messages-area {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
  background-color: #ffffff;
}

.welcome-message {
  text-align: center;
  padding: 40px 20px;
  color: #6b7280;
}

.welcome-content h3 {
  margin: 0 0 16px 0;
  color: #374151;
}

.welcome-content p {
  margin: 0 0 24px 0;
  line-height: 1.6;
}

.example-inputs h4 {
  margin: 0 0 12px 0;
  color: #374151;
  font-size: 14px;
}

.example-item {
  background-color: #f3f4f6;
  border: 1px solid #d1d5db;
  border-radius: 8px;
  padding: 12px 16px;
  margin: 8px 0;
  cursor: pointer;
  transition: all 0.2s;
  text-align: left;
  max-width: 400px;
  margin-left: auto;
  margin-right: auto;
}

.example-item:hover {
  background-color: #e5e7eb;
  border-color: #9ca3af;
  transform: translateY(-1px);
}

.message {
  display: flex;
  margin-bottom: 16px;
  animation: fadeIn 0.3s ease-out;
}

@keyframes fadeIn {
  from { opacity: 0; transform: translateY(10px); }
  to { opacity: 1; transform: translateY(0); }
}

.message.user {
  justify-content: flex-end;
}

.message.assistant .message-content {
  background-color: #f1f5f9;
  border: 1px solid #e2e8f0;
}

.message.user .message-content {
  background-color: #dbeafe;
  border: 1px solid #bfdbfe;
}

.message-avatar {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 16px;
  margin: 0 12px;
  flex-shrink: 0;
}

.message.user .message-avatar {
  order: 2;
}

.message-content {
  max-width: 70%;
  padding: 12px 16px;
  border-radius: 12px;
  position: relative;
}

.message.user .message-content {
  border-radius: 12px 12px 4px 12px;
}

.message.assistant .message-content {
  border-radius: 12px 12px 12px 4px;
}

.message-header {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 4px;
  font-size: 11px;
  color: #6b7280;
}

.message-status {
  padding: 2px 6px;
  border-radius: 10px;
  font-size: 10px;
  font-weight: 500;
}

.message-status.sending {
  background-color: #fef3c7;
  color: #92400e;
}

.message-status.success {
  background-color: #d1fae5;
  color: #065f46;
}

.message-status.error {
  background-color: #fee2e2;
  color: #991b1b;
}

.message-text {
  color: #374151;
  line-height: 1.5;
}

.assistant-content {
  background-color: rgba(0, 0, 0, 0.05);
  padding: 12px;
  border-radius: 8px;
  font-size: 14px;
  overflow-x: auto;
}

.markdown-content {
  line-height: 1.6;
  color: #374151;
}

.markdown-content h1,
.markdown-content h2,
.markdown-content h3,
.markdown-content h4,
.markdown-content h5,
.markdown-content h6 {
  margin: 16px 0 8px 0;
  font-weight: 600;
  color: #1f2937;
}

.markdown-content h1 { font-size: 1.5em; }
.markdown-content h2 { font-size: 1.3em; }
.markdown-content h3 { font-size: 1.1em; }

.markdown-content p {
  margin: 8px 0;
}

.markdown-content ul,
.markdown-content ol {
  margin: 8px 0;
  padding-left: 20px;
}

.markdown-content li {
  margin: 4px 0;
}

.markdown-content blockquote {
  border-left: 4px solid #e5e7eb;
  margin: 12px 0;
  padding: 8px 16px;
  background-color: #f9fafb;
  color: #6b7280;
}

.markdown-content code {
  background-color: #f3f4f6;
  padding: 2px 4px;
  border-radius: 4px;
  font-family: 'Courier New', monospace;
  font-size: 0.9em;
  color: #dc2626;
}

.markdown-content pre {
  background-color: #1f2937;
  color: #f9fafb;
  padding: 12px;
  border-radius: 6px;
  overflow-x: auto;
  margin: 8px 0;
  font-family: 'Courier New', monospace;
  font-size: 13px;
}

.markdown-content pre code {
  background: none;
  padding: 0;
  color: inherit;
}

.markdown-content table {
  border-collapse: collapse;
  width: 100%;
  margin: 8px 0;
}

.markdown-content th,
.markdown-content td {
  border: 1px solid #e5e7eb;
  padding: 8px 12px;
  text-align: left;
}

.markdown-content th {
  background-color: #f9fafb;
  font-weight: 600;
}

.markdown-content a {
  color: #3b82f6;
  text-decoration: none;
}

.markdown-content a:hover {
  text-decoration: underline;
}

.markdown-content strong {
  font-weight: 600;
}

.markdown-content em {
  font-style: italic;
}

.markdown-content hr {
  border: none;
  border-top: 1px solid #e5e7eb;
  margin: 16px 0;
}

.input-area {
  background-color: #ffffff;
  border-top: 1px solid #e5e7eb;
  padding: 16px;
}

.error-message {
  display: flex;
  align-items: center;
  justify-content: space-between;
  background-color: #fee2e2;
  border: 1px solid #fca5a5;
  border-radius: 6px;
  padding: 8px 12px;
  margin-bottom: 12px;
  color: #991b1b;
  font-size: 14px;
}

.close-error {
  background: none;
  border: none;
  color: #991b1b;
  cursor: pointer;
  font-size: 16px;
  font-weight: bold;
  padding: 0;
  margin-left: 8px;
}

.input-container {
  display: flex;
  gap: 12px;
  align-items: flex-end;
}

.message-input {
  flex: 1;
  border: 1px solid #d1d5db;
  border-radius: 8px;
  padding: 12px;
  font-size: 14px;
  resize: vertical;
  min-height: 44px;
  font-family: inherit;
}

.message-input:focus {
  outline: none;
  border-color: #3b82f6;
  box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
}

.message-input:disabled {
  background-color: #f9fafb;
  color: #6b7280;
  cursor: not-allowed;
}

.send-btn {
  padding: 12px 20px;
  background-color: #3b82f6;
  color: white;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  font-weight: 500;
  transition: background-color 0.2s;
  height: fit-content;
}

.send-btn:hover:not(:disabled) {
  background-color: #2563eb;
}

.send-btn:disabled {
  background-color: #9ca3af;
  cursor: not-allowed;
}

.input-tips {
  display: flex;
  justify-content: space-between;
  margin-top: 8px;
  font-size: 12px;
  color: #6b7280;
}

@media (max-width: 768px) {
  .dify-workflow-chat {
    height: 100vh;
    border-radius: 0;
  }
  
  .chat-header {
    padding: 12px 16px;
  }
  
  .header-controls {
    width: 100%;
    justify-content: space-between;
  }
  
  .messages-area {
    padding: 16px;
  }
  
  .message-content {
    max-width: 85%;
  }
  
  .input-container {
    flex-direction: column;
    gap: 8px;
  }
  
  .send-btn {
    width: 100%;
  }
  
  .input-tips {
    flex-direction: column;
    gap: 4px;
  }
}
</style>